/*
 * @Description: 层级组件 - 表格组件
 * @Author: Rfan
 * @Date: 2022-06-21 10:25:48
 * @LastEditTime: 2023-03-06 21:00:27
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Space, Table } from 'antd';
import { debounce } from 'lodash-es';
import classNames from 'classnames/bind';
import update from 'immutability-helper';
import { fetchReciprocalSign, getFileNote } from '@/api/archives/operate';
import { isNullObj } from '@/utils';
import { selectItemByKey } from '@/utils/list';
import { useLevelTableContext } from '../contexts/LevelTableContext';
import Preview from '@/components/Preview';
import EditArchiveItem from './dialogs/EditArchiveItem';
import DetailArchiveItem from './dialogs/DetailArchiveItem';
import { useFormatMessage } from '@/utils/intlHelpers';
import ProForma from '@/components/LevelLayout/components/dialogs/ProForma';
import type { CSSProperties } from 'react';
import type { IPageQuery } from '@/interfaces/global';
import type { IDeleteArchiveParams, IDeleteEArchiveParams } from '@/api/archives/archives';
import type { ColumnsType } from 'antd/es/table';
import type { RowClassName } from 'rc-table/lib/interface';
import styles from '../styles/levelTable.module.scss';
import ReciprocalSign from '@/components/LevelLayout/components/dialogs/ReciprocalSign';
import MediumPoint from './dialogs/MediumPoint';
import { mediaAnchor } from '@/api/search';

const cx = classNames.bind(styles);

const videoExts = ['mp4', 'avi', 'flv', 'wmv'];
const audioExts = ['mp3', 'wav', 'flac', 'ogg'];
const mediaExts = videoExts.concat(audioExts, videoExts);

const LevelTableList = (props: any) => {
  const { type } = props;
  const {
    baseInfo,
    selectItems,
    isComputeHeight,
    list,
    setEntryList,
    tableHeight,
    setSelectedItem,
    fetchMethod,
    selectChange,
    upperFields,
    upperInfo,
    deleteItem,
    listQuery,
    setListQuery
  } = useLevelTableContext();
  const { level, levelNum } = baseInfo;

  const formatMessage = useFormatMessage();

  // 表格loading状态
  const [loading, setLoading] = useState(false);
  // 总页数
  const [total, setTotal] = useState(0);
  //
  const [fieldList, setFieldList] = useState([]);
  const [downLevel, setDownLevel] = useState<any>({});
  // 编辑弹窗状态
  const [editDialogVisible, setEditDialogVisible] = useState(false);
  // 详情弹窗状态
  const [detailDialogVisible, setDetailDialogVisible] = useState(false);
  // 预览弹窗状态
  const [previewDialogVisible, setPreviewDialogVisible] = useState(false);
  // 选中条目ID
  const [clickItemId, setClickItemId] = useState(0);
  // 编辑弹窗数据
  const [editData, setEditData] = useState({});
  // 编辑媒体锚点状态
  const [mediumDialogVisible, setMediumDialogVisible] = useState(false);
  const [mediumData, setMediumData] = useState([]);
  // 表格样式
  const [tableStyle, setTableStyle] = useState<CSSProperties>({});
  // 备考表相关
  const [proFormaVisible, setProFormaVisible] = useState(false);
  const [proData, setProData] = useState({});
  // 互见号相关
  const [reciprocalSignVisible, setReciprocalSignVisible] = useState(false);
  const [reciprocalSignData, setReciprocalSignData] = useState({});
  useEffect(() => {
    if (isComputeHeight && tableHeight) {
      setTableStyle({ height: `${tableHeight}px`, overflowX: 'hidden', overflowY: 'auto' });
    } else if (!isNullObj(tableStyle)) {
      setTableStyle({});
    }
  }, [isComputeHeight, tableHeight]);

  useEffect(() => {
    if (baseInfo?.clear) {
      clearList(true);
      return;
    }
    if (baseInfo?.param && !isNullObj(baseInfo.param)) {
      console.log('table useEffect baseInfo', baseInfo.param);
      setListQuery(update(listQuery, { $merge: { param: baseInfo.param } }));
    }
  }, [baseInfo]);

  useEffect(() => {
    console.log('listQuery', listQuery);

    if (listQuery?.param && !isNullObj(listQuery.param)) {
      setLoading(true);
      fetchMethod(listQuery)
        .then((res: any) => {
          const _data = res.data;
          if (_data.results) {
            setEntryList(_data.results.data || []);
            setTotal(_data.totalCount);
            setFieldList(_data.results.fields);
            setDownLevel(_data.results.downLevel);
            if (_data.results.data) {
              setClickItemId(_data.results.data[0]?.id || 0);
              selectChange(_data.results.downLevel, _data.results.data[0], _data.results.fields);
            } else {
              selectChange({}, {}, {}, true);
            }
          } else {
            clearList(true);
            selectChange({}, {}, {}, true);
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  const clearList = (notifyOutside?: boolean) => {
    setEntryList([]);
    setTotal(0);
    setSelectedItem([]);
    setClickItemId(0);
    notifyOutside && selectChange({ clear: true }, null);
  };

  /**
   * @description: 案卷表格选中相关
   * @param {number} selectedRowKeys
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectedItem(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectedRowKeys: selectItems,
    onChange: onSelectChange
  };

  const rowClassFunc: RowClassName<any> = (record): string => {
    return record.id === clickItemId ? cx('table-row-click') : '';
  };

  /**
   * @description: 列表选中条目方法
   * @param {any} record 选中的条目
   */
  const selectRow = (record: any) => {
    setClickItemId(record.id);
    selectChange(downLevel, record, fieldList);
  };

  /**
   * @description: 双击行方法
   * @param {any} record 选中的条目
   */
  const doubleClickTable = (record: any) => {
    setEditData(record);
    setPreviewDialogVisible(true);
  };

  // 切换页码触发
  const pageChange = (page: number, pageSize: number) => {
    setListQuery(
      update(listQuery, {
        $apply: (state: IPageQuery) => ({
          ...state,
          pageNo: page,
          params: pageSize
        })
      })
    );
  };

  /**
   * @description: 打开编辑弹窗方法
   * @param {any} data 编辑的内容
   */
  const showEditDialog = (data: any) => {
    setEditData(data);
    setEditDialogVisible(true);
  };

  /**
   * @description: 打开详情弹窗方法
   * @param {any} data 编辑的内容
   */
  const showDetailDialog = (data: any) => {
    setEditData(data);
    setDetailDialogVisible(true);
  };

  /**
   * @description: 打开媒体弹窗方法
   * @param {any} data 编辑的内容
   */
  const showMediumDialog = (data: any) => {
    setClickItemId(data.id);
    mediaAnchor({ mediaUrl: data.file_url }).then((res) => {
      const { data } = res;
      setMediumData(data.mediaAnchorList);
      setMediumDialogVisible(true);
    });
  };
  /**
   * @description: 删除选中条目
   * @param {number} id
   */
  const delSelectFile = (id: number) => {
    const params: IDeleteArchiveParams | IDeleteEArchiveParams = {
      atCode: baseInfo.atCode,
      atType: baseInfo.atType,
      level: baseInfo.level,
      commonParams: {
        dbName: baseInfo.param.commonParams.dbName
      },
      entryIdList: [id]
    };
    deleteItem(baseInfo.level, params, '确认删除该条目？');
  };

  const ProFormaForm = (data: any) => {
    const location = {
      atCode: baseInfo.atCode,
      atType: baseInfo.atType,
      dbName: baseInfo.dbName
    };
    // 准备备考表内容
    /* 掉个接口在这里 */
    getFileNote({ entryId: data.id, ...location }).then((res) => {
      const { data } = res;
      setProData(data);
      setProFormaVisible(true);
    });
  };
  const reciprocalSign = (data: any) => {
    const location = {
      sourceArchiveTypeId: baseInfo.archiveTypeId,
      sourceDbName: baseInfo.dbName,
      sourceEntryId: data.id,
      sourceFondsId: baseInfo.fondId,
      sourceLevel: baseInfo.level
    };
    fetchReciprocalSign({ ...location }).then((res) => {
      const { data } = res;
      setReciprocalSignData({ data, location });
      setReciprocalSignVisible(true);
    });
  };
  const actionCol: ColumnsType = [
    {
      title: formatMessage('tableAction'),
      key: 'action',
      fixed: 'right',
      render: (_text, record: any) => {
        return (
          <Space>
            {baseInfo.level !== 0 && (
              <Button
                type="link"
                onClick={(evt) => {
                  evt.stopPropagation();
                  showEditDialog(record);
                }}
              >
                编辑
              </Button>
            )}
            {baseInfo.level !== 0 && (
              <Button
                type="link"
                onClick={(evt) => {
                  evt.stopPropagation();
                  showDetailDialog(record);
                }}
              >
                详情
              </Button>
            )}
            <Button
              type="text"
              danger
              onClick={(evt) => {
                evt.stopPropagation();
                delSelectFile(record.id);
              }}
            >
              删除
            </Button>
            {level === 2 && type !== 0 && (
              <Button
                onClick={(evt) => {
                  evt.stopPropagation();
                  ProFormaForm(record);
                }}
                type="link"
              >
                备考表
              </Button>
            )}
            {levelNum === 1 && type !== 0 && (
              <Button
                onClick={(evt) => {
                  evt.stopPropagation();
                  reciprocalSign(record);
                }}
                type="link"
              >
                互见号
              </Button>
            )}
            {level === 0 && mediaExts.indexOf(record.file_ext) >= 0 && (
              <Button
                type="link"
                onClick={(evt) => {
                  evt.stopPropagation();
                  showMediumDialog(record);
                }}
              >
                媒体锚点信息
              </Button>
            )}
          </Space>
        );
      }
    }
  ];

  const genColumns = (): ColumnsType => {
    const columns: ColumnsType = fieldList.map((field) => {
      const { field_desc: title, field_name: key } = field;
      return {
        title,
        dataIndex: key,
        key,
        render: (val) => {
          const fieldItem: any = selectItemByKey(key, fieldList, 'field_name');
          if (fieldItem?.dict_type_id) {
            return val?.name;
          }
          return val;
        }
      };
    });
    return list.length > 0 ? [...columns, ...actionCol] : columns;
  };

  return (
    <div>
      {useMemo(
        () => (
          <Table
            columns={genColumns()}
            dataSource={list}
            loading={loading}
            rowKey="id"
            rowSelection={rowSelection}
            rowClassName={rowClassFunc}
            scroll={{ x: 'max-content' }}
            size="small"
            pagination={{
              current: listQuery?.pageNo,
              pageSize: listQuery?.pageSize,
              total,
              showTotal: (total) => `共 ${total} 条`,
              onChange: pageChange
            }}
            bordered
            style={tableStyle}
            onRow={(record) => ({
              onClick: debounce(() => {
                selectRow(record);
              }, 200),
              onDoubleClick: () => {
                doubleClickTable(record);
              }
            })}
          />
        ),
        [selectItems, loading, list, listQuery, clickItemId]
      )}

      {/* 编辑弹窗 */}
      {useMemo(
        () => (
          <EditArchiveItem
            visible={editDialogVisible}
            coordinate={{ atCode: baseInfo.atCode, atType: baseInfo.atType, level: baseInfo.level }}
            data={editData}
            onClose={() => {
              setEditDialogVisible(false);
            }}
          />
        ),
        [editDialogVisible]
      )}

      {/* 详情弹窗 */}
      {useMemo(
        () => (
          <DetailArchiveItem
            visible={detailDialogVisible}
            data={editData}
            onClose={() => {
              setDetailDialogVisible(false);
            }}
          />
        ),
        [detailDialogVisible]
      )}

      {/* 预览弹窗 */}
      {useMemo(
        () => (
          <>
            {baseInfo.level === 0 && list.length > 0 && (
              <Preview
                visible={previewDialogVisible}
                title="pic"
                data={editData}
                list={list}
                onClose={() => {
                  setPreviewDialogVisible(false);
                }}
                upper={upperInfo}
                fields={upperFields}
                baseInfo={baseInfo}
              />
            )}
          </>
        ),
        [previewDialogVisible]
      )}
      {/* 备考表 */}
      {useMemo(
        () => (
          <ProForma
            visible={proFormaVisible}
            data={proData}
            baseInfo={baseInfo}
            type={1}
            onClose={() => setProFormaVisible(false)}
          />
        ),
        [proFormaVisible, proData]
      )}
      {/* 互见号 */}
      {useMemo(
        () => (
          <ReciprocalSign
            visible={reciprocalSignVisible}
            BaseData={reciprocalSignData}
            baseInfo={baseInfo}
            type={1}
            onClose={() => setReciprocalSignVisible(false)}
          />
        ),
        [reciprocalSignVisible, reciprocalSignData]
      )}
      {/* 媒体锚点 */}
      {useMemo(
        () => (
          <MediumPoint
            visible={mediumDialogVisible}
            data={mediumData}
            baseInfo={baseInfo}
            entityId={clickItemId}
            type={1}
            onClose={() => setMediumDialogVisible(false)}
          />
        ),
        [mediumDialogVisible, mediumData]
      )}
    </div>
  );
};

export default LevelTableList;
